/**
 * 图片上传
 */
<template>
	<div class="w100">
		<el-upload 
			v-if="!disabled"
			action="" 
			multiple 
			:before-upload="beforeUpload" 
			:show-file-list="false"
			accept=".jpg,.jpeg,.gif,.png,.webp"
			style="display: flex;"
		>
			<vp-btn :loading="loading" type="primary" class="mr-20">
				<slot v-if="$slots.header" name="header"/>
				<div v-else>
					<vp-label zh="上传" en="Upload"/>
					<SvgIcon name="ele-Upload" class="el-icon--right"></SvgIcon>
				</div>
			</vp-btn>
		</el-upload>
		<el-upload 
			v-if="previewList.length > 0"
			action="" 
			list-type="picture-card"
			v-model:file-list="previewList"
			class="mt8"
			:on-preview="handlePictureCardPreview"
    		:on-remove="handleRemove"
			:disabled="disabled"
		>
		</el-upload>

		<el-image-viewer
			v-if="dialogVisible"
			:url-list="[dialogImageUrl]"
			hide-on-click-modal
			teleported
			@close="dialogVisible = false"
		/>
	</div>
</template>
<script setup lang="ts" name="vpImageUpload">
import { ref, computed } from 'vue';
import request from '/@/utils/request';

const modelValue = defineModel({ type: Array, default: [] });
const emits = defineEmits(['change']);

const props = defineProps({
	disabled: {
		type: Boolean,
		default: false,
	},
});

const loading = ref(false);

const dialogImageUrl = ref('');
const dialogImageName = ref('');
const dialogVisible = ref(false);

// 上传文件之前的方法
const beforeUpload = (file: any) => {
	if (file) {
		let submitData = new FormData();
		submitData.append('file', file);
		loading.value = true;
		request.post(`/file/upload`, submitData, { headers: { 'content-type': 'multipart/form-data' } }).then(res => {
			loading.value = false;
			if (res.data && res.data.length) {
				modelValue.value = [...modelValue.value, ...res.data];
				emits("change", modelValue.value);
			}
		});
	}
	return false;
};

// 所有可预览图片
const previewList = computed(() => {
	return modelValue.value.map((obj: any) => {
		return {
			id: obj.id,
			name: obj.yswjm + '.' + obj.hzm,
			url: `${import.meta.env.VITE_API_URL}/file/stream/${obj.id}`,
		}
	})
});


// 预览图片
const handlePictureCardPreview = (uploadFile: any) => {
	dialogImageUrl.value = uploadFile.url!;
	dialogImageName.value = uploadFile.name;
  	dialogVisible.value = true;

}

// 删除图片
const handleRemove = (uploadFile: any) => {
	const index = modelValue.value.findIndex((obj: any) => { return obj.id === uploadFile.id});
	modelValue.value.splice(index, 1);
	emits("change", modelValue.value);
}

</script>
<style scoped>
	:deep(.el-upload--picture-card) {
		display: none;
	}
</style>
